package com.efounder.form.comp;

import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.util.Linkify;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.widget.EditText;

import com.efounder.builder.base.data.DataSetEvent;
import com.efounder.builder.base.data.DataSetListener;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.form.DMColComponent;
import com.efounder.form.DMComponent;
import com.efounder.form.DataSetComponent;
import com.efounder.form.application.FormViewContainer;
import com.efounder.form.base.IComponent;
import com.efounder.form.model.JSONFormModel;
import com.efounder.form.util.FormCompUtil;
import com.efounder.frame.ViewSize;
import com.efounder.util.AppContext;

/**
 * Created by Javor on 16/9/7.
 */

public class FormTextInput extends EditText implements IComponent,IUIComponent,DMComponent,DMColComponent,DataSetListener {
    public static final String TEXT_TYPE_TEXT = "text";
    public static final String TEXT_TYPE_NUMBER = "number";

    //////////////////解决滑动冲突相关属性//////////////////////
    /* 垂直是否可滚动的原始值 */
    private Boolean canScrollVerticallyOriginal = null;
    private int downX;
    private int downY;
    /////////////////////////////////////////
    private String id;

    private int height;
    private int width;

    private int percentWidth;
    private int percentHeight;

    private int gap;

    private String dataSetID;
    private String dataSetColID;

    private DataSetComponent dataSetComponent;
    private EFDataSet dataSet;
    private EFRowSet mainRowSet;

    private boolean canEdit;

    private ViewSize size = new ViewSize(0,0);
    private int paddingLeft = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,4,getResources().getDisplayMetrics());
    private int paddingTop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,5,getResources().getDisplayMetrics());
    private int fontSize;

    private IUIComponent parentComp;

    private boolean editable;

    private boolean visible;
    /** FormTextInput 联动的dataSetColIDs,多个dataSetColID用 “;” 分割**/
    private String linkedDataSetColIDs ;
    private String originalText;

    private int degree = -1;
    private String textType = TEXT_TYPE_TEXT;

    private boolean autoLink;

    public FormTextInput(){
        super(AppContext.getInstance());
        this.setTextColor(Color.BLACK);
        this.setBackgroundColor(Color.parseColor("#E5E5E5"));
    }

    public FormTextInput(Context context) {
        super(context);
    }

    public FormTextInput(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void creationComplete() {
        this.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.i("-----","beforeTextChanged==" + s + "--start:" + start + "--count:" + count + "--after:" + after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.i("-----","onTextChanged==" + s + "--start:" + start + "--count:" + count + "--before:" + before);
                if (TEXT_TYPE_NUMBER.equals(textType) && degree != -1){
                    s = controlDegree(s);
                }
                if (mainRowSet == null) return;
                mainRowSet.put(dataSetColID,s.toString());
                if (linkedDataSetColIDs == null) return;
                String[] linkedDataSetColArray = linkedDataSetColIDs.split(";");
                for (String linkedDataSetColID:linkedDataSetColArray) {
                    mainRowSet.put(linkedDataSetColID,s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private CharSequence controlDegree(CharSequence s){
        if (s.toString().contains(".")) {
            if (s.length() - 1 - s.toString().indexOf(".") >  degree) {
                s = s.toString().subSequence(0,s.toString().indexOf(".") + ( degree+1));
                setText(s);
                setSelection(s.length());
            }
        }
        if (s.toString().trim().substring(0).equals(".")) {
            s = "0" + s;
            setText(s);
            setSelection(2);
        }
        if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
            if (!s.toString().substring(1, 2).equals(".")) {
                setText(s.subSequence(0, 1));
                setSelection(1);
            }
        }
        return s;
    }

    public void dataChanged(EFDataSet dataSet) {
        mainRowSet = dataSet.getCurrentRowSet();
        if (mainRowSet == null) return;
//        String value = mainRowSet.getString(dataSetColID, null);//Integer时，或不不到
        Object value = mainRowSet.getObject(dataSetColID, null);//有值
        if (value == null){
            value = originalText;
        }
        if (value == null){
            value = "";
        }

        if (!getText().toString().equals(value + "")){
            setText(value + "");
        }
    }

    @Override
    public DataSetComponent getDataSetComponent() {
        return dataSetComponent;
    }

    @Override
    public void setDataSetComponent(DataSetComponent dsc) {
        if (dataSetComponent != null)
            dataSetComponent.removeDMComponent(this);
        dataSetComponent = dsc;
        if (dataSetComponent != null)
            dataSetComponent.insertDMComponent(this);
    }

    public void setDataSetComponent(JSONFormModel dsc) {
        if (dataSetComponent != null)
            dataSetComponent.removeDMComponent(this);
        dataSetComponent = dsc;
        if (dataSetComponent != null)
            dataSetComponent.insertDMComponent(this);
    }

    @Override
    public void setLayout() {
        FormCompUtil.setLayoutSize(this);
        this.setPadding(paddingLeft,0,paddingLeft,paddingTop);
    }

    @Override
    public void setDataSetID(String dataSetID) {
        this.dataSetID = dataSetID;
    }

    @Override
    public String getDataSetColID() {
        return dataSetColID;
    }

    @Override
    public void setDataSetColID(String dataSetColID) {
        this.dataSetColID = dataSetColID;
    }

    @Override
    public String getDataSetNameColID() {
        return null;
    }

    @Override
    public void setDataSetNameColID(String value) {

    }

    @Override
    public String getInternalDataSetID() {
        return null;
    }

    @Override
    public void setInternalDataSetID(String dataSetID) {

    }

    @Override
    public void setViewDataSetID(String viewDataSetID) {

    }

    @Override
    public String getViewDataSetID() {
        return null;
    }

    @Override
    public void setViewDataSetColID(String viewDataSetColID) {

    }

    @Override
    public String getViewDataSetColID() {
        return null;
    }

    @Override
    public void setValueDataSetColID(String valueDataSetColID) {

    }

    @Override
    public String getValueDataSetColID() {
        return null;
    }

    @Override
    public Boolean getIsUserInternalDataSetID() {
        return null;
    }

    @Override
    public void setIsUserInternalDataSetID(Boolean v) {

    }

    @Override
    public String getIdentifier() {
        return null;
    }

    @Override
    public Object getPropertyMap() {
        return null;
    }

    @Override
    public void setPropertyMap(Object value) {

    }

    @Override
    public Object getProperty(String key, Object defVal) {
        return null;
    }

    @Override
    public void setProperty(String key, Object value) {

    }

    @Override
    public int getNumberPrecision() {
        return 0;
    }

    @Override
    public void seNumberPrecision(int value) {

    }

    @Override
    public String getNumberFormat() {
        return null;
    }

    @Override
    public void setNumberFormat(String numberFormat) {

    }

    @Override
    public String getColumnType() {
        return null;
    }

    @Override
    public void setColumnType(String value) {

    }

    @Override
    public String getEditorType() {
        return null;
    }

    @Override
    public void setEditorType(String value) {

    }

    @Override
    public String getDateFormat() {
        return null;
    }

    @Override
    public void setDateFormat(String dateFormat) {

    }

    @Override
    public String getFormulaOne() {
        return null;
    }

    @Override
    public void setFormulaOne(String formulaOne) {

    }

    @Override
    public String getEditMask() {
        return null;
    }

    @Override
    public void setEditMask(String editMask) {

    }

    @Override
    public String getFkeyID() {
        return null;
    }

    @Override
    public void setFkeyID(String fkey) {

    }

    @Override
    public String getRlglID() {
        return null;
    }

    @Override
    public void setRlglID(String rlglID) {

    }

    @Override
    public String getDataSetID() {
        return dataSetID;
    }

    @Override
    public void setDataSet(EFDataSet dataSet) {
        if ( this.dataSet != dataSet ) {
            if ( this.dataSet != null ) this.dataSet.removeDataSetListener(this);
            this.dataSet = dataSet;
            if ( this.dataSet != null ) this.dataSet.addDataSetListener(this);
            this.dataChanged(dataSet);
        }

    }

    @Override
    public EFDataSet getDataSet() {
        return dataSet;
    }

    @Override
    public EFRowSet getMainRowSet() {
        return mainRowSet;
    }

    @Override
    public void dataSetChanged(DataSetEvent event) {
        dataChanged(event.getDataSet());
    }

    @Override
    public String getID() {
        return id;
    }

    @Override
    public void setID(String id) {
        this.id = id;
    }

    @Override
    public int getGap() {
        return gap;
    }

    @Override
    public void setGap(int gap) {
        this.gap = gap;
    }

    @Override
    public void setCompWidth(int width) {
        this.width = width;
    }

    @Override
    public int getCompWidth(){
        return this.width;
    }

    @Override
    public void setCompHeight(int height) {
        this.height = height;
    }

    @Override
    public int getCompHeight() {
        return this.height;
    }

    @Override
    public int getPercentWidth() {
        return percentWidth;
    }

    @Override
    public void setPercentWidth(int percentW) {
        percentWidth = percentW;
    }

    @Override
    public int getPercentHeight() {
        return percentHeight;
    }

    @Override
    public void setPercentHeight(int percentH) {
        percentHeight = percentH;
    }

    @Override
    public ViewSize getViewSize() {
        return size;
    }

    @Override
    public void setViewSize(ViewSize size) {
        this.size = size;
    }
    public boolean getCanEdit() {
        return canEdit;
    }

    public void setCanEdit(boolean canEdit) {
        this.canEdit = canEdit;
        this.setFocusable(canEdit);
    }
    public void setCanEdit(Boolean canEdit) {
        if(canEdit){
            this.setFocusable(true);
            setFocusableInTouchMode(true);
            requestFocus();
        }else{
            this.setFocusable(false);
            setFocusableInTouchMode(false);
            //requestFocus();
        }
        this.canEdit = canEdit;
        this.setFocusable(canEdit);
    }
    public int getFontSize() {
        return fontSize;
    }

    public void setFontSize(int fontSize) {
        this.fontSize = fontSize;
        this.setTextSize(Float.parseFloat(fontSize+""));
    }
    @Override
    public int getPaddingLeft() {
        return paddingLeft;
    }

    public void setPaddingLeft(int paddingLeft) {
        this.paddingLeft = paddingLeft;
    }
    @Override
    public int getPaddingTop() {
        return paddingTop;
    }

    public void setPaddingTop(int paddingTop) {
        this.paddingTop = paddingTop;
    }

    @Override
    public IUIComponent getParentComp() {
        return parentComp;
    }

    @Override
    public void setParentComp(IUIComponent comp) {
        parentComp = comp;
    }

    public boolean isEditable() {
        return editable;
    }

    public void setEditable(Boolean editable) {
        this.editable = editable;
        if(editable) {
            this.setFocusable(true);
            setFocusableInTouchMode(true);
            requestFocus();
        }else{
            this.setFocusable(false);
        }
    }

    public boolean isVisible() {
        return visible;
    }

    public void setVisible(boolean visible) {
        this.visible = visible;
        if (visible){
            setVisibility(VISIBLE);
        }else{
            setVisibility(INVISIBLE);
        }
    }

    public String getLinkedDataSetColIDs() {
        return linkedDataSetColIDs;
    }

    public void setLinkedDataSetColIDs(String linkedDataSetColIDs) {
        this.linkedDataSetColIDs = linkedDataSetColIDs;
    }

    public String getOriginalText() {
        return originalText;
    }

    public void setOriginalText(String originalText) {
        this.originalText = originalText;
    }

    public int getDegree() {
        return degree;
    }

    public void setDegree(int degree) {
        this.degree = degree;
    }

    public String getTextType() {
        return textType;
    }

    public void setTextType(String textType) {
        this.textType = textType;
        if (TEXT_TYPE_NUMBER.equals(textType)){
            this.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        }else {
            this.setInputType(InputType.TYPE_CLASS_TEXT);
        }
    }

    public boolean isAutoLink() {
        return autoLink;
    }

    public void setAutoLink(boolean autoLink) {
        this.autoLink = autoLink;
        if(autoLink)
            this.setAutoLinkMask(Linkify.PHONE_NUMBERS);
    }

    public String getStringText() {
        return super.getText().toString();
    }


    /**
     * 初始化原始值
     */
    private void initOriginalValue(){
        if (canScrollVerticallyOriginal == null) {
            canScrollVerticallyOriginal = canScrollVertically(0);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                initOriginalValue();
                downX = (int) event.getX();
                downY = (int) event.getY();
                if (canScrollVerticallyOriginal){
                    FormViewContainer.setDisallowIntercept(true);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                int mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
                int moveY = (int) event.getY();
                if (Math.abs(moveY - downY) > mTouchSlop){//检测滑动
                    if (moveY > downY){//向下滑动
                        if (canScrollVerticallyOriginal && getScrollY() > 0){
                            FormViewContainer.setDisallowIntercept(true);
                        }else {
                            FormViewContainer.setDisallowIntercept(false);
                        }
                    }else {//向上滑动
                        if (canScrollVertically(0)){
                            FormViewContainer.setDisallowIntercept(true);
                        }else {
                            FormViewContainer.setDisallowIntercept(false);
                        }
                    }
                }
                break;
            default:
                FormViewContainer.setDisallowIntercept(false);
                break;
        }

        return super.onTouchEvent(event);
    }
}
